package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.stereotype.Component;

import pojo.User;
import dao.UserDao;

@Component(value="userdao")
public class UserDaoImpl implements UserDao{

	public UserDaoImpl() {
		System.out.println("dao");
	}
	
//	@Resource(name="jndiDataSource")
	private DataSource ds;
	

	public void setDs(DataSource ds) {
		this.ds = ds;
	}

	@Override
	public User addUser(User user) {
		String sql = "insert into qquser(id,uname,pwd,age) values(?,?,?,?)";	
		Connection con=null;
		PreparedStatement pst =null;
		try {
			con = ds.getConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, UUID.randomUUID().toString());
			pst.setString(2, user.getUname());
			pst.setString(3, user.getPwd());
			pst.setDouble(4, user.getAge());
			pst.executeUpdate();
			con.close();
			pst.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}

	@Override
	public User findByName(String name, String pwd) {
		String sql = "select * from qquser where uname=? and pwd=?";
		Connection con=null;
		PreparedStatement pst =null;
		ResultSet rs = null;
		User user = null;
		try {
			con = ds.getConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, name);
			pst.setString(2, pwd);

			rs = pst.executeQuery();
			if(rs.next()){
				user = new User(rs.getString(1), rs.getString(2), rs.getString(3), rs.getInt(4));
				System.out.println(user);
			}
			
			con.close();
			pst.close();
			rs.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}

}
